package com.ruoyi.rsikManage.service.Impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.rsikManage.Access.AccessDatabaseTest;
import com.ruoyi.rsikManage.domain.BroadCast;
import com.ruoyi.rsikManage.domain.enums.BroadcastManufactureTypeEnum;
import com.ruoyi.rsikManage.domain.vo.*;
import com.ruoyi.rsikManage.mapper.BroadcastMapper;
import com.ruoyi.rsikManage.service.BroadcastService;
import com.ruoyi.rsikManage.service.JyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class BroadcastServiceImpl implements BroadcastService {
    @Autowired
    BroadcastMapper broadcastMapper;
    RestTemplate restTemplate = new RestTemplate();
    @Value("${BROADCAST_SYSTEM_IP}")
    private String BROADCAST_SYSTEM_IP;
    @Value("${BROADCAST_SYSTEM_PORT}")
    private String BROADCAST_SYSTEM_PORT;
    @Value("${BROADCAST_SYSTEM_SWITCH}")
    private boolean BROADCAST_SYSTEM_SWITCH;


    @Value("${broadcast.switch}")
    private boolean BroadcastSwitch;

    @Value("${broadcast.manufacture}")
    private String BROADCAST_MANUFACTURE;

    @Value("${broadcast.ip}")
    private String BROADCAST_IP;

    @Value("${broadcast.port}")
    private String BROADCAST_PORT;

    @Value("${broadcast.broadcast_manufacture_type}")
    private Integer BROADCAST_MANUFACTURE_TYPE;


    @Autowired
    JyService jyService;


    @Override
    public void updateBroadCastList()   {
        String jsonStr = demoStr;

        if (BroadcastSwitch) {
            switch (BROADCAST_MANUFACTURE_TYPE) {
                case BroadcastManufactureTypeEnum.YGSJ: {
                    String url = "http://" + BROADCAST_IP + ":" + BROADCAST_PORT + "/broadcast/getterminals";
                    jsonStr = restTemplate.getForObject(url, String.class);
                    break; // 加上 break 结束当前 case 的执行
                }
                case BroadcastManufactureTypeEnum.HUA_LUO: {
                    String url = "http://" + BROADCAST_IP + ":" + BROADCAST_PORT + "/atstar/index.php/bcconftask-interface/querybroadcastobject";
//                    String url = "http://localhost:8080/ISAPI/atstar/index.php/bcconftask-interface/querybroadcastobject";
                    try {
                        // 发送 GET 请求并接收响应
                         jsonStr = restTemplate.getForObject(url, String.class);

                        // 使用 Jackson ObjectMapper 解析 JSON
                        ObjectMapper mapper = new ObjectMapper();
                        JsonNode rootNode = mapper.readTree(jsonStr);

                        // 提取 data 层的内容
                        JsonNode dataNode = rootNode.get("data");
                        if (dataNode != null) {
                            // 将 dataNode 转换成字符串
                             jsonStr = dataNode.toString();
                            // 返回 data 层的内容字符串
                        } else {
                            // 如果没有找到 data 层，返回空或者适当的默认值
                        }
                    } catch (JsonProcessingException e) {
                        // 处理 JSON 解析异常
                        e.printStackTrace(); // 或者记录日志
                    }
                    break; // 加上 break 结束当前 case 的执行
                }
                case BroadcastManufactureTypeEnum.WANG_LING_XUZHOU: {
                    try {
                        AccessDatabaseTest accessDatabaseTest = new AccessDatabaseTest();
                        org.json.JSONArray tlistData = accessDatabaseTest.getTlistData();
                        // 将 JSONArray 转换为字符串
                        jsonStr = tlistData.toString();
                } catch (Exception e) {
                        // 处理 JSON 解析异常
                        e.printStackTrace(); // 或者记录日志
                    }
                    break; // 加上 break 结束当前 case 的执行
                }
                // 可以在需要的情况下添加其他 case
            }
        }
//
        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
        ArrayList<BroadCast> list = new ArrayList<>(jsonArray.size());



        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            switch (BROADCAST_MANUFACTURE_TYPE) {

                case BroadcastManufactureTypeEnum.YGSJ: {
                    list.add(
                            new BroadCast(null,
                                    jsonObject.getInteger("ID"),
                                    jsonObject.getString("TerminalName"),
                                    null)
                    );
                    break; // 加上 break 结束当前 case 的执行
                }
                case BroadcastManufactureTypeEnum.HUA_LUO: {
                    list.add(
                            new BroadCast(null,
                                    jsonObject.getInteger("phone_number"),
                                    jsonObject.getString("phone_name"),
                                    jsonObject.getInteger("dis_group_id")
                            )
                    );
                    break; // 加上 break 结束当前 case 的执行
                }

                case BroadcastManufactureTypeEnum.WANG_LING_XUZHOU: {
                    list.add(
                            new BroadCast(null,
                                    jsonObject.getInteger("devCode"),
                                    jsonObject.getString("terName"),
                                    jsonObject.getInteger("groupId")
                            )
                    );
                    break; // 加上 break 结束当前 case 的执行
                }

            }
        //
        }

        try {
            broadcastMapper.mergeBroadCastListToBroadCastTable(list);
            // 如果没有抛出异常，说明 mergeBroadCastListToBroadCastTable 方法成功执行
            broadcastMapper.deleteBroadCastNotInList(list);
            // 如果没有抛出异常，说明 deleteBroadCastNotInList 方法成功执行
            ;
        } catch (Exception e) {
            // 处理异常情况
            System.err.println("An error occurred: " + e.getMessage());
        }
    }

    @Override
    public AjaxResult updateBroadCastListV2()   {
        String jsonStr = demoStr;

        if (BroadcastSwitch) {
            switch (BROADCAST_MANUFACTURE_TYPE) {
                case BroadcastManufactureTypeEnum.YGSJ: {
                    String url = "http://" + BROADCAST_IP + ":" + BROADCAST_PORT + "/broadcast/getterminals";
                    jsonStr = restTemplate.getForObject(url, String.class);
                    break; // 加上 break 结束当前 case 的执行
                }
                case BroadcastManufactureTypeEnum.HUA_LUO: {
//                    String url = "http://" + BROADCAST_IP + ":" + BROADCAST_PORT + "/atstar/index.php/bcconftask-interface/querybroadcastobject";
                    //本次测试用例
                    String url = "http://localhost:8080/ISAPI/atstar/index.php/bcconftask-interface/querybroadcastobject";
                    try {
                        // 发送 GET 请求并接收响应
                        jsonStr = restTemplate.getForObject(url, String.class);

                        // 使用 Jackson ObjectMapper 解析 JSON
                        ObjectMapper mapper = new ObjectMapper();
                        JsonNode rootNode = mapper.readTree(jsonStr);

                        // 提取 data 层的内容
                        JsonNode dataNode = rootNode.get("data");
                        if (dataNode != null) {
                            // 将 dataNode 转换成字符串
                            jsonStr = dataNode.toString();
                            // 返回 data 层的内容字符串
                        } else {
                            // 如果没有找到 data 层，返回空或者适当的默认值
                        }
                    } catch (JsonProcessingException e) {
                        // 处理 JSON 解析异常
                        e.printStackTrace(); // 或者记录日志
                    }
                    break; // 加上 break 结束当前 case 的执行
                }
                // 可以在需要的情况下添加其他 case
            }
        }
//
        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
        ArrayList<BroadCast> list = new ArrayList<>(jsonArray.size());



        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            switch (BROADCAST_MANUFACTURE_TYPE) {

                case BroadcastManufactureTypeEnum.YGSJ: {
                    list.add(
                            new BroadCast(null,
                                    jsonObject.getInteger("ID"),
                                    jsonObject.getString("TerminalName"),
                                    null)
                    );
                    break; // 加上 break 结束当前 case 的执行
                }
                case BroadcastManufactureTypeEnum.HUA_LUO: {
                    list.add(
                            new BroadCast(null,
                                    jsonObject.getInteger("phone_number"),
                                    jsonObject.getString("phone_name"),
                                    jsonObject.getInteger("dis_group_id")
                            )
                    );
                    break; // 加上 break 结束当前 case 的执行
                }

            }
            //
        }

        try {
            broadcastMapper.mergeBroadCastListToBroadCastTable(list);
            // 如果没有抛出异常，说明 mergeBroadCastListToBroadCastTable 方法成功执行
            broadcastMapper.deleteBroadCastNotInList(list);
            // 如果没有抛出异常，说明 deleteBroadCastNotInList 方法成功执行
            return  AjaxResult.success("更新成功");
        } catch (Exception e) {
            // 处理异常情况
            return  AjaxResult.error("更新失败");
        }
    }

    @Override
    public void playBroadCast() {
        switch (BROADCAST_MANUFACTURE_TYPE) {
            case BroadcastManufactureTypeEnum.YGSJ: {


                break; // 加上 break 结束当前 case 的执行
            }
            case BroadcastManufactureTypeEnum.HUA_LUO: {

                break; // 加上 break 结束当前 case 的执行
            }
        }
    }

    @Override
    public List<BroadCast> selectBroadcastList() {
        return broadcastMapper.selectBroadcastList();
    }

    @Override
    public List<BroadCast> selectBroadcastListForUnitCodes(BroadCast broadCast) {
        return broadcastMapper.selectBroadcastListForUnitCodes(broadCast);
    }



    @Override
    public BroadcastAndMonitorsRelResp selectBroadcastAndMonitorsAssociation(Integer broadcastId) {
        return broadcastMapper.selectBroadcastAndMonitorsAssociation(broadcastId);
    }

    @Override
    public void modifyBroadcastAndMonitorsAssociation(BroadcastAndMonitorsRelResq broadcastAndMonitorsRelResq) {
        Integer broadcastId = broadcastAndMonitorsRelResq.getBroadcastId();
        List<String> monitors = broadcastAndMonitorsRelResq.getMonitors();
        Long unitCode = broadcastAndMonitorsRelResq.getUnitCode();
        broadcastMapper.deleteBroadcastAndMonitorsAssociationForUnitCodes(broadcastId,unitCode);
        if (monitors != null && monitors.size() > 0) {
            broadcastMapper.insertBroadcastAndMonitorsAssociationForUnitCodes(unitCode,broadcastId, broadcastAndMonitorsRelResq.getMonitors());
        }
    }

    @Override
    public List<BroadCast> selectMonitorAssociatedBroadcasts(String monitorId) {
        return broadcastMapper.selectMonitorAssociatedBroadcasts(monitorId);
    }

    @Override
    public List<BroadCast> selectMonitorAssociatedBroadcastsForUnitCodes(String monitorId,Long unitCode) {
        return broadcastMapper.selectMonitorAssociatedBroadcastsForUnitCodes(monitorId,unitCode);
    }

    @Override
    public BroadcastAndEquipsRelResp selectBroadcastAndEquipAssociation(Integer broadcastId) {
        return broadcastMapper.selectBroadcastAndEquipAssociation(broadcastId);
    }

    @Override
    public List<BroadCast> selectEquipAssociatedBroadcasts(String equipCode) {
        return broadcastMapper.selectEquipAssociatedBroadcasts(equipCode);
    }

    @Override
    public void modifyBroadcastAndEquipsAssociation(BroadcastAndEquipsRelResq broadcastAndEquipsRel) {
        Integer broadcastId = broadcastAndEquipsRel.getBroadcastId();
        List<String> equips = broadcastAndEquipsRel.getEquips();
        broadcastMapper.deleteBroadcastAndEquipsAssociation(broadcastId);
        if (equips != null && equips.size() > 0) {
            broadcastMapper.insertBroadcastAndEquipsAssociation(broadcastId, broadcastAndEquipsRel.getEquips());
        }    }

    @Override
    public List<GisBroadcastVo> selectAllGisBroadcasts(BroadCast broadcast) {
        return broadcastMapper.selectAllGisBroadcasts(broadcast);
    }

    @Override
    public List<GisBroadcastVo> selectGisBroadcastsHasCoordinates() {
        return broadcastMapper.selectGisBroadcastsHasCoordinates();
    }

    @Override
    public void updateGisBroadcastsCoordinates(GisBroadcastVo gisBroadcastVo) {
        broadcastMapper.updateGisBroadcastsCoordinates(gisBroadcastVo);
    }

    @Override
    public void updateGisBroadcasts3DCoordinates(GisBroadcasts3DVo gisBroadcasts3DVo) {
        broadcastMapper.updateGisBroadcasts3DCoordinates(gisBroadcasts3DVo);
    }

    @Override
    public List<GisBroadcasts3DVo> gisBroadcastsHas3DCoordinates() {
        return broadcastMapper.gisBroadcastsHas3DCoordinates();
    }

    @Override
    public List<GisBroadcasts3DVo> selectAllBroadcasts3D(GisBroadcasts3DVo gisBroadcasts3DVo) {
        return broadcastMapper.selectAllBroadcasts3D(gisBroadcasts3DVo);
    }


    private String demoStr =  "[\n" +
            "    {\n" +
            "        \"ID\": 1,\n" +
            "        \"TerminalName\": \"调度话筒1\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 2,\n" +
            "        \"TerminalName\": \"调度话筒2\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 3,\n" +
            "        \"TerminalName\": \"二采区变电所\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 4,\n" +
            "        \"TerminalName\": \"090203回风顺槽口\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 5,\n" +
            "        \"TerminalName\": \"中央变电所-副井\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 6,\n" +
            "        \"TerminalName\": \"二采区轨道巷450米\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 7,\n" +
            "        \"TerminalName\": \"二采区车场\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 8,\n" +
            "        \"TerminalName\": \"二采区轨道巷\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 9,\n" +
            "        \"TerminalName\": \"永久避难硐室\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 10,\n" +
            "        \"TerminalName\": \"中央变电所\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 11,\n" +
            "        \"TerminalName\": \"Terminal11\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 12,\n" +
            "        \"TerminalName\": \"Terminal12\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 13,\n" +
            "        \"TerminalName\": \"Terminal13\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 14,\n" +
            "        \"TerminalName\": \" 一采区东翼措施巷口\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 15,\n" +
            "        \"TerminalName\": \"100204运输顺槽\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 16,\n" +
            "        \"TerminalName\": \"二采区水泵房\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 17,\n" +
            "        \"TerminalName\": \"一采区东翼轨道巷口\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 18,\n" +
            "        \"TerminalName\": \"100204回风\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 19,\n" +
            "        \"TerminalName\": \"100201回风顺槽\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 20,\n" +
            "        \"TerminalName\": \"1\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 21,\n" +
            "        \"TerminalName\": \"090109\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 22,\n" +
            "        \"TerminalName\": \"090206运输口\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 23,\n" +
            "        \"TerminalName\": \"井底煤仓\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"ID\": 24,\n" +
            "        \"TerminalName\": \"090113运输顺槽\"\n" +
            "    }\n" +
            "]";
}
//
